package com.zycx.system.user.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Description: 密码加密
 * Created by zycx on 2018-12-04 22:14
 * Created with IntelliJ IDEA.
 */
public class PassWordToHash {

    /**
     *   注册时密码加密
     * @param password 用户密码
     * @return 用户密码
     */
    public static String passwordToHash(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(password.getBytes());
            byte[] src = digest.digest();
            StringBuilder stringBuilder = new StringBuilder();
            // 字节数组转16进制字符串
            for (byte aSrc : src) {
                String s = Integer.toHexString(aSrc & 0xFF);
                if (s.length() < 2) {
                    stringBuilder.append('0');
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

    /**
     *  登录时判断密码是否正确
     * @param passWord  登陆用户密码
     * @param dataBasePassWord 数据库密码
     * @return  true / false
     */
    public static boolean comparePassWord(String passWord, String dataBasePassWord) {
        // 将密码加密之后比较
        return passwordToHash(passWord).equals(dataBasePassWord);
    }

}
